package com.yun.algorithmproblem.huaweiod;

public class OD410 {
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
//        int n = sc.nextInt();
//        int m = sc.nextInt();
        int[][] res = matrix(4, 1);
        for (int[] row : res) {
            for (int num : row) {
                if(num!=0){
                    System.out.print(num+" ");
                }else {
                    System.out.print("* ");
                }
            }
            System.out.println();
        }
    }

    private static int[][] matrix(int n, int m) {
        int cols;
        if(n%m==0){
            cols=n/m;
        }else {
            cols = n / m + 1;
        }
        int[][] res = new int[m][cols];
        int up = 0, left = 0, down = m - 1, right = cols - 1;
        int x = 0, y = -1;
        int direction = 0;
        int num = 1;
        while (num <= n) {
            if (direction == 0) {
                for (int i = y+1; i <= right; i++) {
                    res[x][i] = num;
                    num++;
                    if (num > n) {
                        break;
                    }
                }
                y = right;
                direction = 1;
                up++;
            } else if (direction == 1) {
                for (int i = x + 1; i <= down; i++) {
                    res[i][y] = num;
                    num++;
                    if (num > n) {
                        break;
                    }
                }
                x = down;
                direction = 2;
                right--;
            } else if (direction == 2) {
                for (int i = y - 1; i >= left; i--) {
                    res[x][i] = num;
                    num++;
                    if (num > n) {
                        break;
                    }
                }
                y = left;
                direction = 3;
                down--;
            } else if (direction == 3) {
                for (int i = x - 1; i >= up; i--) {
                    res[i][y] = num;
                    num++;
                    if (num > n) {
                        break;
                    }
                }
                x = up;
                direction = 0;
                left++;
            }
        }
        return res;
    }
}
